package com.boby.homecamera.webserver.body

import com.yanzhenjie.andserver.http.ResponseBody
import com.yanzhenjie.andserver.util.MediaType
import java.io.OutputStream
import java.io.RandomAccessFile

class RangeFileBody(
    private val file: java.io.File,
    private val mimeType: MediaType ,
    private val start: Long = 0,
    private val end: Long = file.length() - 1
) : ResponseBody {

    override fun writeTo(outputStream: OutputStream) {
        val buffer = ByteArray(8192)
        RandomAccessFile(file, "r").use { raf ->
            raf.seek(start)
            var bytesRemaining = end - start + 1
            while (bytesRemaining > 0) {
                val read = raf.read(buffer, 0, minOf(buffer.size.toLong(), bytesRemaining).toInt())
                if (read == -1) break
                outputStream.write(buffer, 0, read)
                bytesRemaining -= read
            }
        }
    }
    override fun isRepeatable(): Boolean {
        return true
    }

    override fun isChunked(): Boolean {
      return false
    }

    override fun contentLength(): Long {
        return end - start + 1
    }

    override fun contentType()= mimeType

}
